package com.glorystone.ins.service.impl;

import com.glorystone.ins.beanUtils.CharUtils;
import com.glorystone.ins.dao.CapitalRecordMapper;
import com.glorystone.ins.dao.OrderMapper;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.common.util.ServiceValidate;
import com.glorystone.ins.domain.*;
import com.glorystone.ins.domain.Attachment.BusinessTypeEnum;
import com.glorystone.ins.enums.*;
import com.glorystone.ins.domain.BusinessLog;
import com.glorystone.ins.domain.CapitalRecord;
import com.glorystone.ins.domain.Order;
import com.glorystone.ins.domain.Order.AdvanceFundType;
import com.glorystone.ins.domain.SysUser;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.*;
import com.glorystone.ins.vo.*;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@Transactional(readOnly = true)
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CapitalRecordMapper capitalRecordMapper;

    @Autowired
    private AuditTaskService auditTaskService;
    @Autowired
    private BusinessLogService businessLogService;
    @Autowired
    private ProductSvr productSvr;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private AdvanceService advanceService;
    @Autowired
    private CreditTotalService creditTotalService;
    @Autowired
    private InsurerService insurerService;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private CapitalRecordService capitalRecordService;

    @Transactional(readOnly = false)
    public int modifyOrder(Order order) {
        int state = orderMapper.updateOrderSelective(order);
        return state;
    }

    @Override
    public List<Order> findOrderList(String channelId, String ordNum, String insurant, Date insureStartDate) {
        return orderMapper.findOrderList(channelId, ordNum, insurant, insureStartDate);
    }

    @Override
    public Order findOrderByCode(String ordercode) {
        return orderMapper.findOrderByCode(ordercode);
    }

    @Override
    @Transactional(readOnly = false)
    public int insertOrder(Order order, String[] typeInsurance) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        //投保类型默认为续保，如果传过来为空置1
        if (order.getTypeInvestment() == null) {
            order.setTypeInsurance(1);
        }
        //车辆类型默认为客车，如果传过来为空值默认值1
        if (order.getVehicleType() == null) {
            order.setVehicleType(1);
        }
        //状态为驳回可编辑
        if (order.getStatus() != null) {
            //编辑完毕进入待审核
            if (MainOrderStatusEnum.TO_EDIT.getIndex() == order.getStatus()) {
                order.setStatus(OrderStatusEnum.TO_AUDIT.getValue());
                order.setChannelStatus(MainOrderStatusEnum.TO_AUDIT.getIndex());
                order.setUpdateDate(new Date());
                order.setUpdateBy(user.getTid());
                int insert = orderMapper.updateOrderSelective(order);
                return insert;
            }
        } else {
            if (typeInsurance == null) {
                return -3;
            }
            /**
             * 订单编号生成，前几位为保险公司标识
             */
            // TODO: 2018/3/14
            if (typeInsurance.length > 0) {
                //订单录入值初始状态为待审核
                order.setDelFlag(0);
                order.setStatus(MainOrderStatusEnum.TO_AUDIT.getIndex());
                order.setChannelStatus(OrderStatusEnum.TO_AUDIT.getValue());
                //查询登录人的用户信息
                order.setCreateBy(user.getTid());
                order.setUpdateDate(new Date());
                order.setUpdateBy(user.getTid());
                order.setCreateDate(new Date());
                Channel channel = this.findChannel(user);
                if (channel != null) {
                    /**
                     * channel type代表个人或公司渠道
                     */
                    Integer type1 = channel.getType();
                    if (type1 != null) {
                        /**
                         * 如果个人或渠道在申请订单时都未达到通过审核状态，表示没有下单资格
                         */
                        if (channel.getStatus() == Channel.StatusEnum.CREATE_CHANNEL.getValue() || channel.getStatus() == Channel.StatusEnum.CHANNEL_AUDIT_REJECT.getValue()) {
                            return -1;
                        }
                    }
                    Long tid = channel.getTid();
                    if (tid != null) {
                        order.setChannelId(tid);
                    } else {
                        log.info("渠道id为空，请输入渠道登录信息");
                    }
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                Date currenttime = new Date();
                String acturltime = sdf.format(currenttime);
                for (int i = 0; i < typeInsurance.length; i++) {
                    String insyrerId ="OD";
                    if (insyrerId != null) {
                        /**
                         * 订单创建规则:保单固定好+渠道id+时间年月日时分秒以及i
                         */
                        String ordernumber = insyrerId + channel.getTid() + acturltime + i;
                        order.setOrdCode(ordernumber);
                        String str = typeInsurance[i];
                        //产品类型
                        order.setTypeInsurance(Integer.parseInt(str.substring(str.length() - 1)));
                        //产品id
                        order.setProductId(Long.parseLong(str.substring(0, str.length() - 1)));
                        //订单插入由于订单自增长，需要清空tid
                        if (order.getTid() != null) {
                            order.setTid(null);
                        }
                        int insert = orderMapper.insert(order);
                        if (insert > 0) {
                            System.out.println("ordertid---------------" + order.getTid());
                            //插入成功调用流程接口进入待办
                            auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, order.getTid(), FlowOperateTypeEnum.START);
                            //操作记录插入
                            businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, order.getTid(), BusinessLog.ContentEnum.CREATE_ORDER, BusinessLog.ContentEnum.CREATE_ORDER.getValue());
                        }
                    }
                }
            }
        }
        return -2;
    }

    @Override
    public OrderVo findOrderVoByCode(String ordCode) {
        /**
         * 订单列表都是渠道可以查看
         * 根据登录用户信息取出渠道tid作为主查询条件
         */
        if (ordCode == null) {
            log.debug("订单编号为空，请重新输入：");
            return null;
        }
        log.debug("订单详情查询开始，订单编号为" + ordCode);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();

        OrderVo orderVoByCode = null;

        if (user != null) {
            int userLevel = user.getUserLevel();
            if(userLevel==1){
               return  orderMapper.findOrderVoByCode(null, ordCode);
            }
            Integer type = user.getType();
            if (type != null) {
                try {
                    Channel channel = channelService.findByUserId(user.getTid());
                    if (channel != null) {
                        Long tid = channel.getTid();
                        if (tid != null) {
                            /**
                             * tid 渠道id
                             */
                            orderVoByCode = orderMapper.findOrderVoByCode(tid, ordCode);
                        }
                    }
                } catch (Exception e) {
                    log.error("订单详情查询异常：" + e.toString());
                }
            }
        }
        return orderVoByCode;
    }

    //报表导出功能
    @Override
    public List<OrderVo> findOrderVoList(String ordNum, String insurant, String insureStartDate, int i) {
        log.info("入参：" + "ordNum" + ordNum, "insurant" + insurant, "insureStartDate" + insureStartDate, "type" + i);
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if (user != null) {
try {
                        Channel channel = channelService.findByUserId(user.getTid());
                        if (channel != null) {
                            Long tid = channel.getTid();
                            if (tid != null) {
                                List<OrderVo> orderVoExportList = orderMapper.findOrderVoExportList(tid, ordNum, insurant, CharUtils.stringToDate(insureStartDate), i);
                                        for(OrderVo orderVo :orderVoExportList){
                                            if(orderVo.getTypeInsurance()==0){
                                                orderVo.setTypeInsurances("交强险");
                                            }else {
                                                orderVo.setTypeInsurances("商业险");
                                            }
                                            if(orderVo.getChannelStatus()==1){
                                                orderVo.setChannelStatusName("待审核");
                                            }else if(orderVo.getChannelStatus()==2){
                                                orderVo.setChannelStatusName("待支付");
                                            }else if(orderVo.getChannelStatus()==3){
                                                orderVo.setChannelStatusName("待生成保单");
                                            }else if(orderVo.getChannelStatus()==4){
                                                orderVo.setChannelStatusName("待确认定价");
                                            }else if(orderVo.getChannelStatus()==5){
                                                orderVo.setChannelStatusName("已拒绝定价");
                                            }else if(orderVo.getChannelStatus()==6){
                                                orderVo.setChannelStatusName("被驳回");
                                            }else if(orderVo.getChannelStatus()==7){
                                                orderVo.setChannelStatusName("待返佣");
                                            }else if(orderVo.getChannelStatus()==8){
                                                orderVo.setChannelStatusName("待还款");
                                            }else if(orderVo.getChannelStatus()==9){
                                                orderVo.setChannelStatusName("支付失败");
                                            }else if(orderVo.getChannelStatus()==10){
                                                orderVo.setChannelStatusName("授信不足");
                                            }else if(orderVo.getChannelStatus()==11){
                                                orderVo.setChannelStatusName("已结算");
                                            }else if(orderVo.getChannelStatus()==12){
                                                orderVo.setChannelStatusName("待退保结算");
                                            }else if(orderVo.getChannelStatus()==13){
                                                orderVo.setChannelStatusName("已退保结算");
                                            }else if(orderVo.getChannelStatus()==14){
                                                orderVo.setChannelStatusName("已退保结算");
                                            }
                                        }
                                return orderVoExportList;
                            } else {
                                log.info("渠道id为空，请输入渠道登录信息");
                            }
                        }
                    } catch (Exception e) {
                        log.error("报表导出异常", e.toString());
                        throw  new RuntimeException("报表导出异常，请联系相关人员");
                 }
        }
        return null;
    }

    @Override
    public Order selectOrderInfo(OrderQueryConditionVo order) {
        log.debug("根据订单ID查询订单信息开始");
        Order orderInfo = null;
        try {
            if (order != null) {
                log.debug("订单编号ID是" + order.getTid());
                orderInfo = orderMapper.selectByPrimaryKey(order.getTid());
            } else {
                log.debug("order为空，无法获取查询条件");
            }
        } catch (Exception e) {
            log.error("根据订单ID查询订单信息异常", e.toString());
        }
        log.debug("根据订单Id查询订单信息结束");
        return orderInfo;
    }

    @Override
    public PageList<OrderViewVO> selectorderList(PageVo vo) {
        PageList<OrderViewVO> list = orderMapper.selectOrderList(vo, vo.getPageable());
        return list;
    }

    @Override
    @Transactional(readOnly = false)
    public OperateResult resetOrder(OrderQueryConditionVo orderCondition, OperateResult jsonResult) {
        log.debug("审核驳回订单开始");
        try {
            /**
             * 订单审核拒绝
             */
            auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, orderCondition.getTid(), FlowOperateTypeEnum.REJECT);
            /**
             * 修改订单表状态
             */
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            Order order = new Order();
            order.setTid(orderCondition.getTid());
            order.setStatus(OrderStatusEnum.TO_EDIT.getValue());
            order.setChannelStatus(MainOrderStatusEnum.TO_EDIT.getIndex());
            order.setUpdateBy(user.getTid());
            order.setUpdateDate(new Date());
            int num = orderMapper.updateOrderSelectiveById(order);
            /**
             * 添加审核操作记录
             */
            businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, orderCondition.getTid(), BusinessLog.ContentEnum.RESET_ORDER, orderCondition.getRemark());
        } catch (Exception e) {
            jsonResult.setMsg("审核驳回订单异常");
            log.error("审核驳回订单异常", e);
            throw new RuntimeException("审核驳回操作数据库异常");
        }
        jsonResult.setMsg("审核驳回订单成功");
        jsonResult.setSuccess(true);
        log.debug("审核驳回订单结束");
        return jsonResult;
    }

    @Override
    @Transactional(readOnly = false)
    public OperateResult passOrder(OrderQueryConditionVo order, OperateResult jsonResult) {
        log.debug("订单审核通过开始");
        try {
            /**
             * 获取当前登陆人信息
             */
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            /**
             * 查询当前订单信息
             */
            Order orderInfo = orderMapper.selectByPrimaryKey(order.getTid());
            /**
             * 创建当前订单的资金流水记录
             */
            List<CapitalRecord> capitalRecords = createCaptialRecord(orderInfo, order, user);
            if(!order.isFlag()){
                for (CapitalRecord capitalRecord : capitalRecords) {
                    capitalRecordMapper.updateByPrimaryKeySelective(capitalRecord);
                }
            }else{
                capitalRecordMapper.insertList(capitalRecords);
            }
            /**
             * 修改订单信息状态
             */
            orderInfo = creatUpdateOrder(orderInfo, order, user);
            orderMapper.updateOrderSelectiveById(orderInfo);
            /**
             * 调用流程提交接口
             */
            auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, order.getTid(), FlowOperateTypeEnum.PASS);
            /**
             * 调用添加操作记录接口
             */
            businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, order.getTid(), BusinessLog.ContentEnum.CHANNEL_AUDIT_PASS, order.getRemark());
        } catch (Exception e) {
            log.error("订单ID" + order.getTid() + "的审核通过异常", e);
            jsonResult.setMsg("审核通过订单异常");
            throw new RuntimeException("审核通过操作数据库异常");
        }
        jsonResult.setSuccess(true);
        jsonResult.setMsg("订单审核通过成功");
        log.debug("订单ID" + order.getTid() + "的审核通过结束");
        return jsonResult;
    }

    private Order creatUpdateOrder(Order orderInfo, OrderQueryConditionVo order, SysUser user) {
        orderInfo.setProductId(order.getProductId());
        if (Order.TypeInsuranceEnum.SALI.getValue() == orderInfo.getTypeInsurance()) {
            orderInfo.setPulsoryPremium(order.getPremium());
            orderInfo.setVechcleVesselTax(order.getVehicleTex());
        } else if (Order.TypeInsuranceEnum.COMMERCE_INSURANCE.getValue() == orderInfo.getTypeInsurance()) {
            orderInfo.setMercialPremium(order.getPremium());
        }
        orderInfo.setAllPremium(order.getAllPremium());
        orderInfo.setTexPremium(order.getTexPremium());
        orderInfo.setPaySubject(order.getThemeKey());
        orderInfo.setFollowPoint(order.getFollowPoint());
        orderInfo.setReplenishPoint(order.getSupplementPoint());
        orderInfo.setChannelRebate(order.getChannelPoint());
        orderInfo.setChannelLookRebate(order.getChannelLookPoint());
        orderInfo.setStatus(OrderStatusEnum.TO_CONFIRM.getValue());
        orderInfo.setChannelStatus(MainOrderStatusEnum.TO_ACK_PRICE.getIndex());
        orderInfo.setUpdateDate(new Date());
        orderInfo.setUpdateBy(user.getTid());
        return orderInfo;
    }

    private List<CapitalRecord> createCaptialRecord(Order orderInfo, OrderQueryConditionVo order, SysUser user) {
        List<CapitalRecord> capitalRecords = capitalRecordService .selectOrderCapitalRecord(order);
        CapitalRecord channelRecord = new CapitalRecord();
        CapitalRecord insurerRecord = new CapitalRecord();
        if (capitalRecords != null && capitalRecords.size() == 2) {
            for (CapitalRecord capitalRecord : capitalRecords) {
                if (OpponentEnum.CHANNEL.getValue() == capitalRecord.getOpponent()) {
                    channelRecord = capitalRecord;
                }else if (OpponentEnum.INSURANCECOMPANY.getValue() == capitalRecord.getOpponent()) {
                    insurerRecord = capitalRecord;
                }
            }
            order.setFlag(false);
        }else {
            order.setFlag(true);
            capitalRecords = new ArrayList<>();
            insurerRecord.setCreateBy(user.getTid());
            insurerRecord.setCreateDate(new Date());
            capitalRecords.add(insurerRecord);
            channelRecord.setCreateBy(user.getTid());
            channelRecord.setCreateDate(new Date());
            capitalRecords.add(channelRecord);
        }
        channelRecord.setOrdId(order.getTid());
        channelRecord.setMustPremium(order.getChannelPayPremium());
        channelRecord.setMustRebateAmt(order.getChannelRebateFee());
        channelRecord.setOpponent(OpponentEnum.CHANNEL.getValue());
        channelRecord.setTradeType(TradeTypeEnums.INSURE.getValue());
        if (Objects.equals(Order.AdvanceFundType.PART_ADVANCE_FUND.getValue(),orderInfo.getTypeInsurance2()) ) {
            channelRecord.setMustRebateAmt(order.getChannelRebateFee());
        } else if (Objects.equals(Order.AdvanceFundType.ALL_ADVANCE_FUND.getValue(),orderInfo.getTypeInsurance2())) {
            channelRecord.setMustRebateAmt(order.getChannelRebateFee());
        }
        channelRecord.setRemark(order.getRemark());
        channelRecord.setUpdateBy(user.getTid());
        channelRecord.setUpdateDate(new Date());
        /**
         * 组装保险公司资金流水
         */

        insurerRecord.setOrdId(order.getTid());
        insurerRecord.setMustPremium(order.getAllPremium());
        insurerRecord.setOpponent(OpponentEnum.INSURANCECOMPANY.getValue());
        insurerRecord.setTradeType(TradeTypeEnums.INSURE.getValue());
        insurerRecord.setRemark(order.getRemark());
        insurerRecord.setFollowRpoundage(order.getTexPremium().multiply(
                order.getFollowPoint()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
        insurerRecord.setReplenishRpoundage(order.getTexPremium().multiply(
                order.getSupplementPoint()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
        insurerRecord.setMustRebateAmt(insurerRecord.getFollowRpoundage().add(
                insurerRecord.getReplenishRpoundage()));
        insurerRecord.setUpdateBy(user.getTid());
        insurerRecord.setUpdateDate(new Date());
        return capitalRecords;
    }
    /************************************已结算订单模块************************************************/
    /**
     * 查询保险公司已结算订单
     *
     * @param vo
     * @return
     */
    @Override
    public PageList<OrderVo> getInsyrerData(PageVo vo) {
        String insurerIds = getInsurerId();
        return orderMapper.getInsyrerDataOrderData(insurerIds, vo, vo.getPageable());
    }

    @Override
    public PageList<OrderVo> findOrderVoList(Long tid, PageVo vo) {
        PageList<OrderVo> orderVoList = orderMapper.findOrderVoList(tid, vo, vo.getPageable());
        return orderVoList;
    }

    private String getInsurerId() {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        StringBuilder ids = new StringBuilder();
        if (user != null) {
            List<InsurerUser> list = insurerService.getSlaesmenByUserId(user.getTid());
            for (InsurerUser i : list) {
                ids.append(i.getInsurerId() + ",");
            }
        } else {
            log.info("-------登录超时---------");
        }
        if (StringUtils.isNotBlank(ids.toString())) {
            String insurerIds = ids.substring(0, ids.lastIndexOf(","));
            return insurerIds;
        } else {
            return null;
        }
    }

    /**
     * 渠道已结算订单
     *
     * @param vo
     * @return
     */
    @Override
    public PageList<OrderVo> getChannelData(PageVo vo) {
        String insurerIds = getInsurerId();
        return orderMapper.getChannelDataOrderData(insurerIds, vo, vo.getPageable());
    }

    /**
     * 下载替换字段
     *
     * @param order
     */
    private void changeValue(OrderVo order) {
        if (Product.TypeStatusEnum.COMPULSORY_INSURANCE.getValue().equals(order.getTypeInsurance())) {
            order.setTypeInsurances("交强险");
        } else {
            order.setTypeInsurances("商业险");
        }
        if(order.getPaySubject()!=null){
            switch (order.getPaySubject()) {
                case 1:
                    order.setPaySubjects("环宇康泰");
                    break;
                case 2:
                    order.setPaySubjects("青岛盛达");
                    break;
                case 3:
                    order.setPaySubjects("玉环天云");
                    break;
                case 4:
                    order.setPaySubjects("汉龙");
                    break;
                default:
                    break;
            }
        }

        if (StringUtils.isEmpty(order.getCompanyRegisterName())) {
            order.setCompanyRegisterName(order.getName());
        }
    }

    /**
     * 已结算保险公司订单下载
     *
     * @param insyrerId
     * @param ordNum
     * @param channelId
     * @param insureStartDate
     * @param insureEndDate
     * @param plateNum
     * @param user
     * @return
     */
    @Override
    public List<OrderVo> findAlreadPayCompany(String insyrerId, String ordNum, String channelId, String insureStartDate, String insureEndDate, String plateNum, SysUser user) {
        //String insurerIds = getInsurerId();
        List<OrderVo> orderVoList = orderMapper.findAlreadPayCompany(user, insyrerId, ordNum, channelId, insureStartDate, insureEndDate, plateNum);
        for (OrderVo order : orderVoList) {
            try {
                changeValue(order);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("---------------值替换失败-----------------------");
            }
            if(order.getCheckResult()!=null){
                switch (order.getCheckResult()) {
                    case 1:
                        order.setCheckResults("一致");
                        break;
                    case 2:
                        order.setCheckResults("不一致");
                        break;
                    default:
                        break;
                }
            }

        }
        return orderVoList;
    }

    /**
     * 已结算渠道订单下载
     *
     * @param insyrerId
     * @param ordNum
     * @param channelId
     * @param insureStartDate
     * @param insureEndDate
     * @param plateNum
     * @param user
     * @return
     */
    @Override
    public List<OrderVo> findAlreadPayChannel(String insyrerId, String ordNum, String channelId, String insureStartDate, String insureEndDate, String plateNum, SysUser user) {
        List<OrderVo> orderVoList = orderMapper.findAlreadPayChannel(user, insyrerId, ordNum, channelId, insureStartDate, insureEndDate, plateNum);
        for (OrderVo order : orderVoList) {
            try {
                changeValue(order);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("---------------值替换失败-----------------------");
            }
        }
        return orderVoList;
    }

    @Override
    @Transactional(readOnly = false)
    public int modifyPayState(Order order, Long tid, String ordmessage,FlowOperateTypeEnum flowOperateTypeEnum) {
        log.info("入参：tid" + tid + "<-------------->ordmessage" + ordmessage);
        log.info("----------------------->order.getChannelStatus:"+order.getChannelStatus()+"---------------------->order.getStatus():"+order.getStatus());
        int i = 0;
        try {
            i = orderMapper.updateOrderSelective(order);
            log.info("插入是否成功，i:"+i);
            if (i > 0) {
                auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, order.getTid(), flowOperateTypeEnum);
                businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, tid, BusinessLog.ContentEnum.AGREE_ORDER, ordmessage);
            }
        } catch (Exception e) {
            log.error("确认定价状态修改信息异常：" + e.getMessage());
            throw new RuntimeException("确认定价状态修改信息异常"+"订单状态为"+order.getStatus()+"渠道状态编号为"+order.getChannelStatus());
        }
        return i;
    }

    @Override
    public List<OrderViewVO> downLoadNeedPay(Long insurerId1, String plateNum1, String channelId1, int themeKey, int orderStatus) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<OrderViewVO> orderViewVOS = orderMapper.downLoadNeedPay(user, insurerId1, plateNum1, channelId1, themeKey, orderStatus);
        for(OrderViewVO orderViewVO:orderViewVOS){
            if(orderViewVO.getStatus()==1){
                orderViewVO.setStrStatus("待审核");
            }else if(orderViewVO.getStatus()==2){
                orderViewVO.setStrStatus("待支付");
            }else if(orderViewVO.getStatus()==3){
                orderViewVO.setStrStatus("待完善");
            }else if(orderViewVO.getStatus()==4){
                orderViewVO.setStrStatus("待渠道确认");
            }else if(orderViewVO.getStatus()==5){
                orderViewVO.setStrStatus("渠道已拒绝");
            }else if(orderViewVO.getStatus()==6){
                orderViewVO.setStrStatus("审核驳回");
            }else if(orderViewVO.getStatus()==7){
                orderViewVO.setStrStatus("已投保");
            }else if(orderViewVO.getStatus()==8){
                orderViewVO.setStrStatus("已退保");
            }else if(orderViewVO.getStatus()==9){
                orderViewVO.setStrStatus("产品变更");
            }else if(orderViewVO.getStatus()==10){
                orderViewVO.setStrStatus("授信不足");
            }else if(orderViewVO.getStatus()==11){
                orderViewVO.setStrStatus("产品变更");
            }else if(orderViewVO.getStatus()==12){
                orderViewVO.setStrStatus("产品不可用");
            }else{
                orderViewVO.setStrStatus("产品变更");
            }

            if(orderViewVO.getTypeInsurance()==0){
                orderViewVO.setTypeInsurances("交强险");
            }else if(orderViewVO.getTypeInsurance()==1){
                orderViewVO.setTypeInsurances("商业险");
            }
            if(orderViewVO.getChannel()!=null){
                orderViewVO.setPhone(orderViewVO.getChannel().getContact().getTelephone());
                if(orderViewVO.getChannel().getType()==2){
                    orderViewVO.setChannelName(orderViewVO.getChannel().getCompanyRegisterName());
                }
                if(orderViewVO.getChannel().getType()==1){
                    orderViewVO.setChannelName(orderViewVO.getChannel().getContact().getName());
                }
            }
            if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.HUANYU.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.HUANYU.getDisplay());
            }else if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.QINGDAO.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.QINGDAO.getDisplay());
            }else if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.YUHUAN.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.YUHUAN.getDisplay());
            }else if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.DRAGON.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.DRAGON.getDisplay());
            }
        }
        return orderViewVOS;
    }

    @Override
    @Transactional(readOnly = false)
    public OperateResult payOrder(OrderQueryConditionVo order, OperateResult result) {
        /**
         * 校验订单信息
         */
        Order orderInfo = orderMapper.selectByPrimaryKey(order.getTid());
        if (orderInfo == null) {
            log.debug("订单ID = " + order.getTid() + "订单信息不存在");
            result.setMsg("订单信息不存在，请联系运维");
            return result;
        }
        /**
         * 查询渠道流水信息
         */
        List<CapitalRecord> capitalRecords = capitalRecordMapper.selectRecordByOrderId(order.getTid());
        if (capitalRecords == null || capitalRecords.size() != 2) {
            log.debug("订单ID = " + order.getTid() + "对应的渠道应收保费不存在");
            result.setMsg("渠道应收信息不全");
            return result;
        }
        CapitalRecord channelRecord = null;
        CapitalRecord insurerRecord = null;
        for (CapitalRecord capitalRecord : capitalRecords) {
            if (OpponentEnum.INSURANCECOMPANY.getValue() == capitalRecord.getOpponent()) {
                insurerRecord = capitalRecord;
            } else {
                channelRecord = capitalRecord;
            }
        }
        /**
         * 判断是否需要校验产品信息
         */
        if (1 == order.getPayStatus()) {

            /**
             * 校验产品信息是否失效
             */
            result = checkProductInfo(orderInfo);
            if (result.isSuccess()) {
                return result;
            } else {
                /**
                 * 订单为垫保费订单，需要检查授信信息和今日额度
                 */
                if (Order.AdvanceFundType.ALL_ADVANCE_FUND.getValue() == orderInfo.getTypeInsurance2()) {
                    result = checkChannelInfo(orderInfo, channelRecord);
                    if (!result.isSuccess()) {
                        return result;
                    }
                }
                result = paySuccess(order, orderInfo, channelRecord, insurerRecord);
            }
        } else if (2 == order.getPayStatus()) {
            /**
             * 订单为垫保费订单，需要检查授信信息和今日额度
             */
            if (Order.AdvanceFundType.ALL_ADVANCE_FUND.getValue() == orderInfo.getTypeInsurance2()) {
                result = checkChannelInfo(orderInfo, channelRecord);
                if (!result.isSuccess()) {
                    return result;
                }
            }
            result = paySuccess(order, orderInfo, channelRecord, insurerRecord);
        } else {
            result = payFail(order, orderInfo);
            if (result.isSuccess()) {
                result.setSuccess(false);
                result.setMsg("产品失效导致的支付失败事物异常");
            }
        }
        return result;
    }

    @Override
    public List<OrderViewVO> dwChannelNeedPay(Long insurerId2, String plateNum2, String channelId2, String insurantStartDate,String insurantEndDate ) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<OrderViewVO> orderViewVOS = orderMapper.dwChannelNeedPay(user, insurerId2, plateNum2, channelId2, insurantStartDate,insurantEndDate);
        for(OrderViewVO orderViewVO:orderViewVOS){
                if(orderViewVO.getStatus()==1){
                    orderViewVO.setStrStatus("待审核");
                }else if(orderViewVO.getStatus()==2){
                    orderViewVO.setStrStatus("待支付");
                }else if(orderViewVO.getStatus()==3){
                    orderViewVO.setStrStatus("待完善");
                }else if(orderViewVO.getStatus()==4){
                    orderViewVO.setStrStatus("待渠道确认");
                }else if(orderViewVO.getStatus()==5){
                    orderViewVO.setStrStatus("渠道已拒绝");
                }else if(orderViewVO.getStatus()==6){
                    orderViewVO.setStrStatus("审核驳回");
                }else if(orderViewVO.getStatus()==7){
                    orderViewVO.setStrStatus("已投保");
                }else if(orderViewVO.getStatus()==8){
                    orderViewVO.setStrStatus("已退保");
                }else if(orderViewVO.getStatus()==9){
                    orderViewVO.setStrStatus("产品变更");
                }else if(orderViewVO.getStatus()==10){
                    orderViewVO.setStrStatus("授信不足");
                }else if(orderViewVO.getStatus()==11){
                    orderViewVO.setStrStatus("产品变更");
                }else if(orderViewVO.getStatus()==12){
                    orderViewVO.setStrStatus("产品不可用");
                }else{
                    orderViewVO.setStrStatus("产品变更");
                }

                if(orderViewVO.getTypeInsurance()==0){
                    orderViewVO.setTypeInsurances("交强险");
                }else if(orderViewVO.getTypeInsurance()==1){
                    orderViewVO.setTypeInsurances("商业险");
                }
                if(orderViewVO.getChannel()!=null){
                    orderViewVO.setPhone(orderViewVO.getChannel().getContact().getTelephone());
                    if(orderViewVO.getChannel().getType()==2){
                        orderViewVO.setChannelName(orderViewVO.getChannel().getCompanyRegisterName());
                    }
                    if(orderViewVO.getChannel().getType()==1){
                        orderViewVO.setChannelName(orderViewVO.getChannel().getContact().getName());
                    }
                }

            if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.HUANYU.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.HUANYU.getDisplay());
            }else if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.QINGDAO.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.QINGDAO.getDisplay());
            }else if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.YUHUAN.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.YUHUAN.getDisplay());
            }else if(Objects.equals(orderViewVO.getPaySubject(),RebateSetVo.PaySubjectEnum.DRAGON.getValue())){
                orderViewVO.setPaySubjectName(RebateSetVo.PaySubjectEnum.DRAGON.getDisplay());
            }
        }
        return orderViewVOS;
    }

    private OperateResult paySuccess(OrderQueryConditionVo order, Order orderInfo, CapitalRecord channelRecord, CapitalRecord insurerRecord) {
        OperateResult result = OperateResult.createMsg(false, "成功支付事务开始");
        try {
            /**
             * 垫子类型为垫
             */
            if (Order.AdvanceFundType.ALL_ADVANCE_FUND.getValue() == orderInfo.getTypeInsurance2()) {
                /**
                 * 再用渠道额度
                 */
                creditTotalService.operateCreditQuota(orderInfo.getChannelId(), CreditRecord.TypeEnum.DECREASE, channelRecord.getMustPremium(), null);
                /**
                 * 返还渠道额度
                 */
                advanceService.upActualAmount(channelRecord.getMustPremium());
                channelRecord.setRealRebateAmt(channelRecord.getMustRebateAmt());
                channelRecord.setPayDate(LocalDate.now());
            } else {
                if(order.getFile()!=null){
                    /**
                     * 上传附件
                     */
                    attachmentService.save(order.getFile(), OrderAttachmentType.PAYMENT_VOUCHER.getValue(), "", Attachment.BusinessTypeEnum.ORDER, order.getTid());
                }
            }
            /**
             * 判断渠道的状态，垫资类型是垫返点时，渠道支付保费后，渠道状态为已结算，别的状态是待收付
             */
            if (Order.AdvanceFundType.PART_ADVANCE_FUND.getValue() == orderInfo.getTypeInsurance2()) {
                channelRecord.setStatus(CapitalRecordStatusEnum.SETTLED.getValue());
                channelRecord.setRealRebateAmt(channelRecord.getMustRebateAmt());
                channelRecord.setPayDate(order.getReceiptDate());
            } else {
                channelRecord.setStatus(CapitalRecordStatusEnum.FOR_COLLECTION.getValue());
            }
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            channelRecord.setRealPremium(order.getReceiptChannel());
            channelRecord.setReceiptDate(order.getReceiptDate());
            channelRecord.setUpdateBy(user.getTid());
            channelRecord.setUpdateDate(new Date());
            insurerRecord.setStatus(CapitalRecordStatusEnum.TO_CHECK.getValue());
            insurerRecord.setRealPremium(order.getPayInsurer());
            insurerRecord.setPayDate(order.getPayDate());
            insurerRecord.setUpdateBy(user.getTid());
            insurerRecord.setUpdateDate(new Date());
            /**
             * 记录订单流水记录
             */
            capitalRecordMapper.updateByPrimaryKeySelective(channelRecord);
            capitalRecordMapper.updateByPrimaryKeySelective(insurerRecord);
            orderInfo.setStatus(OrderStatusEnum.TO_PERFECT.getValue());
            orderInfo.setChannelStatus(MainOrderStatusEnum.TO_CREATE_ORDER_NUM.getIndex());
            orderInfo.setUpdateBy(user.getTid());
            orderInfo.setUpdateDate(new Date());
            /**
             * 修改订单状态
             */
            orderMapper.updateOrderSelectiveById(orderInfo);
            /**
             * 添加操作记录
             */
            businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, orderInfo.getTid(), BusinessLog.ContentEnum.PAY_ORDER_SUCCESS, order.getRemark());
            /**
             * dia
             */
            auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, orderInfo.getTid(), FlowOperateTypeEnum.PASS);
        } catch (Exception e) {
            log.error("订单ID=" + orderInfo.getTid() + "的订单支付异常", e);
            result.setMsg("支付异常");
        }
        result.setSuccess(true);
        result.setMsg("支付成功");
        result.setResult("success");
        return result;
    }

    private OperateResult checkChannelInfo(Order order, CapitalRecord capitalRecord) {
        OperateResult result = OperateResult.createMsg(false, "检查渠道信息开始");
        Channel channel = channelService.getById(order.getChannelId());
        if (channel == null || channel.getCreditTotal() == null || channel.getCreditTotal().getDepositAmount() == null) {
            log.debug("订单ID = " + order.getTid() + "对应的渠道信息不存在");
            result.setMsg("渠道授信信息不存在，请联系运维");
            return result;
        }
        if (channel.getCreditTotal().getDepositAmount().compareTo(channel.getCreditTotal().getDepositLastAmount()) > 0) {
            log.debug("订单ID = " + order.getTid() + "对应的渠道保证金不足");
            result.setMsg("保证金额度不足，请让渠道先补足保证金");
            return result;
        }
        if (capitalRecord.getMustPremium().compareTo(channel.getCreditTotal().getLastAmount()) > 0) {
            log.debug("订单ID = " + order.getTid() + "对应的渠道额度不足");
            result = payFail(null, order);
            if (result.isSuccess()) {
                result.setSuccess(false);
                result.setMsg("渠道额度不足，支付失败异常");
            } else {
                result.setMsg("渠道额度不足，支付失败");
            }
            return result;
        }
        Advance advance = advanceService.findTodayAdvance();
        if (advance == null || advance.getTodatAmount() == null || advance.getActualAmount() == null) {
            log.debug("今日垫资额度信息不全");
            result.setMsg("今日垫资额度信息不全");
            return result;
        }

        if (capitalRecord.getMustPremium().compareTo(advance.getTodatAmount().subtract(advance.getActualAmount())) > 0) {
            log.debug("今日垫资额度不足");
            result.setMsg("今日垫资额度不足");
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    private OperateResult checkProductInfo(Order order) {
        OperateResult result = productSvr.checkProductMessage(order.getProductId());
        if (result != null && result.getResult() != null) {
            RebateSetVo rebateSetVo = (RebateSetVo) result.getResult();
            if (rebateSetVo.getStatus() == 0) {
                result.setSuccess(false);
                return result;
            }
        }
        result.setMsg("产品不可用");
        result.setSuccess(true);
        return result;
    }

    private OperateResult payFail(OrderQueryConditionVo order, Order orderInfo) {
        OperateResult result = OperateResult.createMsg(false, "订单支付失败事物开始");
        log.debug("订单ID=" + orderInfo.getTid() + "订单支付失败事物开始");
        try {
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            orderInfo.setUpdateBy(user.getTid());
            orderInfo.setUpdateDate(new Date());
            if (order == null) {
                orderInfo.setStatus(OrderStatusEnum.PAY_FAIL_LACK_CREDIT.getValue());
                orderInfo.setChannelStatus(MainOrderStatusEnum.LESS_CREDIT.getIndex());
                result.setMsg("产品信息失效，支付失败操作成功");
            } else if (4 == order.getPayStatus()) {
                orderInfo.setStatus(OrderStatusEnum.PAY_FAIL_TO_CONFIRM.getValue());
                orderInfo.setChannelStatus(MainOrderStatusEnum.PAY_FAIL.getIndex());
                result.setMsg("产品变更，支付失败操作成功");
            } else {
                orderInfo.setStatus(OrderStatusEnum.PAY_FAIL_TO_EDIT.getValue());
                orderInfo.setChannelStatus(MainOrderStatusEnum.PRODUCT_NO.getIndex());
                result.setMsg("产品不可用，支付失败操作成功");
            }
            orderMapper.updateOrderSelectiveById(orderInfo);
            auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, orderInfo.getTid(), FlowOperateTypeEnum.REJECT, RejectNodeEnum.CHANNEL);
            businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, orderInfo.getTid(), BusinessLog.ContentEnum.PAY_ORDER_FAIL, "支付失败");
            orderMapper.updateOrderSelectiveById(orderInfo);
        } catch (Exception e) {
            log.error("订单ID=" + orderInfo.getTid() + "订单支付失败事物异常", e);
            result.setSuccess(true);
            throw new RuntimeException("订单支付失败事物异常,请联系运维");
        }
        log.debug("订单ID=" + orderInfo.getTid() + "订单支付失败事物结束");
        return result;
    }

    public List<CapitalRecord> selectRecordByOrderId(Long orderId) {
        List<CapitalRecord> list = capitalRecordMapper.selectRecordByOrderId(orderId);
        return list;
    }

    @SuppressWarnings("static-access")
	@Override
    @Transactional(readOnly = false)
    public boolean updateByOrdCode(Order order) {
    	Order orderInfo = orderMapper.findOrderByCode(order.getOrdCode());
    	Integer account = orderInfo.getLaonAccount();
    	if(account!=null){
    		ZoneId zoneId = ZoneId.systemDefault();
    		ZonedDateTime zonedDateTime = order.getDateIssuance().atStartOfDay(zoneId);
    		Instant instant = zonedDateTime.toInstant();
    		Date date = new Date().from(instant);
    		long time = date.getTime();
    		long accountTime = account*24*60*60*1000;
    		long alltime = time+accountTime;
    		Date date2 = new Date(alltime);
    		Instant instant2 = date2.toInstant();
    		ZoneId zone = ZoneId.systemDefault();
    		LocalDate localDate = instant2.atZone(zone).toLocalDate();
    		order.setInsyrerMaturityDate(localDate);
    	}
    	order.setStatus(OrderStatusEnum.INSURED.getValue());
    	if(AdvanceFundType.NO_ADVANCE_FUND.getValue()==order.getTypeInsurance2()){
    		order.setChannelStatus(MainOrderStatusEnum.TO_RAKE_BACK.getIndex());
    	}else if(AdvanceFundType.PART_ADVANCE_FUND.getValue()==order.getTypeInsurance2()){
    		order.setChannelStatus(MainOrderStatusEnum.HAS_BALANCE.getIndex());
    	}else if(AdvanceFundType.ALL_ADVANCE_FUND.getValue()==order.getTypeInsurance2()){
    		order.setChannelStatus(MainOrderStatusEnum.TO_REPAYMENT.getIndex());
    	}
    	businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER,order.getTid(),BusinessLog.ContentEnum.PERFECT_ORDER,null);
        auditTaskService.submit(WorkFlowEnum.CREATE_ORDER,FlowBusinessTypeEnum.ORDER,order.getTid(),FlowOperateTypeEnum.PASS);
        int result = orderMapper.updateByOrdCode(order);
        return result == 1;
    }

    @Override
    @Transactional(readOnly = false)
    public OperateResult payChannelOrder(OrderQueryConditionVo order, OperateResult result) {
        try {

            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            Order orderInfo = new Order();
            orderInfo.setTid(order.getTid());
            orderInfo.setChannelStatus(MainOrderStatusEnum.HAS_BALANCE.getIndex());
            orderInfo.setUpdateDate(new Date());
            orderInfo.setUpdateBy(user.getTid());
            orderMapper.updateOrderSelectiveById(orderInfo);
            CapitalRecord channelRecord = capitalRecordMapper.selectCapitalRecord(order.getTid(), OpponentEnum.CHANNEL.getValue(), TradeTypeEnums.INSURE.getValue());
            channelRecord.setPayDate(order.getPayDate());
            channelRecord.setRealRebateAmt(order.getChannelRebateFee());
            channelRecord.setStatus(CapitalRecordStatusEnum.SETTLED.getValue());
            channelRecord.setRemark(order.getRemark());
            channelRecord.setUpdateDate(new Date());
            channelRecord.setUpdateBy(user.getTid());
            capitalRecordMapper.updateByPrimaryKeySelective(channelRecord);
            businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, order.getTid(), BusinessLog.ContentEnum.PAY_CHANNEL_SUCCESS, order.getRemark());
        } catch (Exception e) {
            log.error("订单ID=" + order.getTid() + "的订单支付渠道返佣费异常", e);
            result.setMsg("支付渠道返佣费异常");
        }
        result.setSuccess(true);
        result.setMsg("支付渠道返佣费成功");
        return result;
    }
    /**
     * 查询渠道汇总信息
     */
    @Override
    public ChannelCountVo countChannelOrderInfo(Long channelId) {
        ChannelCountVo channelCountInfo = new ChannelCountVo();
        ChannelCountVo queryOpenAccount = capitalRecordMapper.queryOpenAccount(channelId);
        if(queryOpenAccount!=null){
            channelCountInfo.setStayRebaseCount(queryOpenAccount.getStayRebaseCount()==null?BigDecimal.ZERO:queryOpenAccount.getStayRebaseCount());
        }else{
            channelCountInfo.setStayRebaseCount(BigDecimal.ZERO);
        }
        ChannelCountVo querySettleAccount = capitalRecordMapper.querySettleAccount(channelId);
        if(querySettleAccount!=null){
            channelCountInfo.setSettledRebaseCount(querySettleAccount.getSettledRebaseCount()==null?BigDecimal.ZERO:querySettleAccount.getSettledRebaseCount());
        }else{
            channelCountInfo.setSettledRebaseCount(BigDecimal.ZERO);
        }
        ChannelCountVo queryStayPremiumCount = capitalRecordMapper.queryStayPremiumCount(channelId);
        if(queryStayPremiumCount!=null){
            channelCountInfo.setStayPremiumCount(queryStayPremiumCount.getStayPremiumCount());
        }
        ChannelCountVo queryUnsureStayAccount = capitalRecordMapper.queryUnsureStayAccount(channelId);
        if(queryUnsureStayAccount!=null){
            if(queryUnsureStayAccount.getUnsureDeductRebaseCount()==null){
                queryUnsureStayAccount.setUnsureDeductRebaseCount(BigDecimal.ZERO);
            }
            if(queryUnsureStayAccount.getUnsureEnrnRebaseCount()==null){
                queryUnsureStayAccount.setUnsureEnrnRebaseCount(BigDecimal.ZERO);
            }
            channelCountInfo.setStayUnsureRebaseCount(queryUnsureStayAccount.getUnsureEnrnRebaseCount().subtract(queryUnsureStayAccount.getUnsureDeductRebaseCount()));
        }else {
            channelCountInfo.setStayUnsureRebaseCount(BigDecimal.ZERO);
        }
        ChannelCountVo queryUnsureSettleAccount = capitalRecordMapper.queryUnsureSettleAccount(channelId);
        if(queryUnsureSettleAccount!=null){
            if(queryUnsureSettleAccount.getUnsureSettleDeductRebaseCount()==null){
                queryUnsureSettleAccount.setUnsureSettleDeductRebaseCount(BigDecimal.ZERO);
            }
            if(queryUnsureSettleAccount.getUnsureSettleEnrnRebaseCount()==null){
                queryUnsureSettleAccount.setUnsureSettleEnrnRebaseCount(BigDecimal.ZERO);
            }
            channelCountInfo.setSettledUnsureRebaseCount(queryUnsureSettleAccount.getUnsureSettleEnrnRebaseCount().
                    subtract(queryUnsureSettleAccount.getUnsureSettleDeductRebaseCount()));
        }else {
            channelCountInfo.setSettledUnsureRebaseCount(BigDecimal.ZERO);
        }
        channelCountInfo.setEarnTotalRebase(channelCountInfo.getStayRebaseCount().
                add(channelCountInfo.getSettledRebaseCount()).
                add(channelCountInfo.getSettledUnsureRebaseCount()).
                add(channelCountInfo.getStayUnsureRebaseCount()));
        return channelCountInfo;
    }

    @Override
    public Channel findChannel(SysUser user) {
        user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Channel byUserId = null;
        if (user != null) {
            Long tid = user.getTid();
            if (tid != null) {
                byUserId = channelService.findByUserId(tid);
            }
        }
        return byUserId;
    }

	@Override
	public Order onlyOrdNum(String ordNum) {
		if(StringUtils.isEmpty(ordNum)){
			ServiceValidate.isTrue(Boolean.FALSE, "保单号不能为空");
		}
		Order order = orderMapper.onlyOrdNum(ordNum);
		return order;
	}

    /**
     * 管理员查询所有
     * @param vo
     * @return
     */
    @Override
    public PageList<OrderVo> findOrderVoListAll(PageVo vo) {
        return orderMapper.findOrderVoListAll(vo,vo.getPageable());
    }

    @Override
    @Transactional(readOnly = false)
    public int modifyProductId(Order order) {
        return  orderMapper.updateOrderSelective(order);
    }

    @Override
    @Transactional(readOnly = false)
    public OperateResult resetOrderDirect(OperateResult operateResult,Long tid) {
        RebateSetVo rebateSetVo = (RebateSetVo)operateResult.getResult();
        if(rebateSetVo==null){
            operateResult.setSuccess(false);
            operateResult.setMsg("计算保费没有返回结果，请联系运维");
            return operateResult;
        }else if(1==rebateSetVo.getStatus()||2==rebateSetVo.getStatus()){
            log.debug("审核驳回订单开始");
            String remark = "";
            try {
                /**
                 * 订单审核拒绝
                 */
                auditTaskService.submit(WorkFlowEnum.CREATE_ORDER, FlowBusinessTypeEnum.ORDER, tid, FlowOperateTypeEnum.REJECT);
                /**
                 * 修改订单表状态
                 */
                SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
                Order order = new Order();
                order.setTid(tid);
                if(1==rebateSetVo.getStatus()){
                    order.setStatus(OrderStatusEnum.CHECK_RESET_TLACK_CREDIT.getValue());
                    order.setChannelStatus(MainOrderStatusEnum.PAY_FAIL.getIndex());
                    remark = "产品不可用，审核直接驳回";
                }else if(2==rebateSetVo.getStatus()){
                    order.setStatus(OrderStatusEnum.CHECK_RESET_TO_CONFIRM.getValue());
                    order.setChannelStatus(MainOrderStatusEnum.PRODUCT_NO.getIndex());
                    remark = "产品变更，审核直接驳回";
                }
                order.setUpdateBy(user.getTid());
                order.setUpdateDate(new Date());
                int num = orderMapper.updateOrderSelectiveById(order);
                /**
                 * 添加审核操作记录
                 */
                businessLogService.save(BusinessLog.BusinessTypeEnum.ORDER, tid, BusinessLog.ContentEnum.RESET_ORDER, remark);
            } catch (Exception e) {
                operateResult.setMsg("审核驳回订单异常");
                log.error("审核驳回订单异常", e);
                throw new RuntimeException("审核驳回操作数据库异常");
            }
            operateResult.setMsg(remark);
        }
        log.debug("审核驳回订单结束");
        return operateResult;
    }
}